<template>
    <el-button
        type="primary"
        @click="getdownloadXlsx"
        :size="size"
        :icon="loading ? 'el-icon-loading' : 'el-icon-download'"
        :disabled="loading"
    >{{$t('m.button.download')}}</el-button>
</template>
<script>
import { formatDate } from "assets/js/date";
const ERR_OK = 200;
export default {
    props: ["columns", "allColumns", "size", "title"],
    data() {
        return {
            loading: false,
            tableData: [],
            filterVal: [],
            tHeader: []
        };
    },
    methods: {
        loadingClose() {
            this.loading = false;
        },
        getdownloadXlsx() {
            this.loading = true;
            this.$emit("getDataxlsx");
        },
        getDataXlsx(data) {
            if (data && data.length > 0 && data instanceof Array) {
                this.filterVal = [];
                this.tHeader = [];
                this.tableData = data;
                this.allColumns.forEach(item => {
                    if (this.columns) {
                        if (!this.columns[item.property]) {
                            this.filterVal.push(item.property);
                            this.tHeader.push(item.label);
                        }
                    } else {
                        this.filterVal.push(item.property);
                        this.tHeader.push(item.label);
                    }
                });
                this.export2Excel();
            } else {
                this.loading = false;
                this.$message.error("没有更多数据");
            }
        },
        // 导出表格
        export2Excel() {
            var that = this;
            require.ensure([], () => {
                const { export_json_to_excel } = require(this.tHeader.indexOf(
                    "图片"
                ) === -1
                    ? "@/excel/Export2Excel"
                    : "@/excel/export2Excelimg"); //这里必须使用绝对路径
                const tHeader = that.tHeader; // 导出的表头名
                const filterVal = that.filterVal; // 导出的表头字段名
                const list = this.tableData;
                const data = that.formatJson(filterVal, list);
                this.loading = false;
                export_json_to_excel(tHeader, data, this.title + formatDate( new Date(), "yyyy-MM-dd hh_mm"));
            });
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => v[j]));
        }
    }
};
</script>
